import axios from "axios";
// 2、多个请求同时出现401时，如何仅调用一次更新token接口（拓展，可选）
// 3、没有限制重新请求的次数，可能会导致无限循环的尝试，请设置最大尝试次数为3次，不考虑重置。/

let isRefreshing = false;
let failedQueue = [];
let retryCount = 0;

const processQueue = (error, token = null) => {
    failedQueue.forEach((prom) => {
        if (error) {
            prom.reject(error);
        } else {
            prom.resolve(token);
        }
    });

    failedQueue = [];
};
axios.interceptors.response.use(
    (response) => response,
    async (error) => {
        const originalRequest = error.config;

        if (error.response && error.response.status === 401 && retryCount < 3) {
            if (!isRefreshing) {
                isRefreshing = true;
                retryCount++;

                try {
                    const newToken = await getNewToken();
                    localStorage.setItem("token", newToken);
                    processQueue(null, newToken);
                    isRefreshing = false;
                    retryCount = 0;
                } catch (err) {
                    processQueue(err, null);
                    isRefreshing = false;
                    retryCount = 0;
                }
            }

            return new Promise((resolve, reject) => {
                failedQueue.push({ resolve, reject });
            })
                .then((token) => {
                    originalRequest.headers["Authorization"] =
                        "Bearer " + token;
                    return axios(originalRequest);
                })
                .catch((err) => {
                    return Promise.reject(err);
                });
        }

        return Promise.reject(error);
    }
);
async function getNewToken() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve("new_token_123");
        }, 1000);
    });
}
